﻿using _5E.Infrastructure.Collections;
using Melee.Contract;
using Melee.Controller.Comet;
using Melee.Controller.Request;
using Melee.Controller.Routing;
using Melee.Controller.Storage;
using Melee.DataContract.Messaging;

namespace Melee.Controller.Handlers
{
    public class LoginHandler : RequestHandler
    {
        private IUserService m_userService = null;

        public LoginHandler(IUserService userService)
            : base(Routes.LOGIN)
        {
            m_userService = userService;
        }

        public override void Handle(WebRequest webRequest)
        {
            if (Route.Matches(webRequest))
            {
                LoginRequest request = new LoginRequest
                {
                    Name = webRequest.QueryArguments.ExtractFor<string>("name"),
                    Password = webRequest.QueryArguments.ExtractFor<string>("password")
                };
                LoginResponse response = m_userService.Login(request);
                webRequest.Storage.Add(HttpStorageKeys.Success, response.Success);
                if (response.Success)
                {
                    UserCookie cookie = new UserCookie
                    {
                        LoginId = response.LoginId,
                        LoginName = request.Name,
                        UserName = response.UserName
                    };
                    cookie.Save();
                    CometObserverFactory.Observer.Add(response.LoginId, cookie.UserName);
                }
                else
                {
                    webRequest.Storage.Add(HttpStorageKeys.Message, response.Message);
                    webRequest.Storage.Add(HttpStorageKeys.Exception, response.Exception);
                }
                webRequest.AsyncResult.SetCompleted();
            }
            else
            {
                base.NextHandler.Handle(webRequest);
            }
        }
    }
}
